package mymyoux.io.apps
{
	import flash.events.Event;
	import flash.events.ServerSocketConnectEvent;
	import flash.net.ServerSocket;
	
	import mymyoux.debug.Log;
	import mymyoux.io.Socket;
	public class MServer
	{
		protected var _socket:ServerSocket;
		public static const MIN_PORT:uint = 1024;
		public static const MAX_PORT:uint = 65535;
		protected var _sockets:Array;
		public function MServer()
		{
			_sockets = new Array();
			_socket = new ServerSocket();
			_socket.addEventListener(Event.CONNECT,onConnect);
			_socket.addEventListener(Event.CLOSE,onClose);
		}
		protected function onConnect(event:ServerSocketConnectEvent):void
		{
			Log.trace(event);
			_sockets.push(new Socket(event.socket));
		}
		protected function onClose(event:ServerSocketConnectEvent):void
		{
			Log.trace(event);
		}
		public function get port():uint
		{
			return _socket.localPort;
		}
		public function close():void
		{
			_socket.close();
			var i:int = 0;
			for(; i<_sockets.length; i++)
			{
				_sockets[i].close();
			}
		}
		public function listen(port:uint = 0, network:String = "0.0.0.0"):void
		{
			var success:Boolean = false;
			if(port<MIN_PORT || port > MAX_PORT)
			{
				port = 0;
			}	
			try{
				_socket.bind(port,network);
				success = true;
			}catch(error:Error)
			{
				Log.warn("Server socket not binded at port : "+port+"\n"+error);
				try{
					_socket.bind(0,network);
					success = true;
				}catch(error2:Error)
				{
					Log.error("Server socket not binded [final] at port : "+port+"\n"+error2);
				}
				
			}
				
			
			if(!success)
			{
				Log.error("impossible de se connecter : port = "+port);
			}else
			{
				port = _socket.localPort;
				Log.debug("connexion réussie : port = "+port);
				try
				{
					_socket.listen();
				}catch(error:Error)
				{
					Log.error("Server socket not opened at port : "+port+"\n"+error);
				}
				
			}
		}

	}
}